package com.etl.sys.service.impl;

import com.etl.sys.entity.SysLock;
import com.etl.sys.mapper.SysLockMapper;
import com.etl.sys.service.ISysLockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 调度锁表 服务实现类
 * </p>
 *
 * @author chenfenghai
 * @since 2020-11-04
 */
@Service
public class SysLockServiceImpl extends ServiceImpl<SysLockMapper, SysLock> implements ISysLockService {

    /**
     * 保存锁信息
     */
    @Override
    public synchronized void saveLock() {
        Integer count = super.lambdaQuery()
                .select(SysLock::getLockId)
                .eq(SysLock::getLockUid, ISysLockService.LOCK_UID)
                .eq(SysLock::getLockType, ISysLockService.LOCK_TYPE_SCHEDULE)
                .count();
        if (Objects.isNull(count) || count <= 0) {
            super.baseMapper.saveLock(ISysLockService.LOCK_UID,
                    ISysLockService.LOCK_TYPE_SCHEDULE, ISysLockService.LOCK_SECOND);
        } else {
            super.baseMapper.updateLock(ISysLockService.LOCK_UID, ISysLockService.LOCK_SECOND);
        }
    }


    /**
     * 是否第一把锁
     *
     * @return boolean
     */
    @Override
    public boolean isFirstLock() {
        super.baseMapper.clearExpiredLock();
        List<SysLock> sysLockList = super.lambdaQuery()
                .select(SysLock::getLockUid)
                .eq(SysLock::getLockType, ISysLockService.LOCK_TYPE_SCHEDULE)
                .orderByAsc(SysLock::getLockId).list();
        return CollectionUtils.isNotEmpty(sysLockList)
                && ISysLockService.LOCK_UID.equals(sysLockList.get(0).getLockUid());
    }

    /**
     * 清空已过期的锁信息
     */
    @Override
    public void clearExpiredLock() {
        super.baseMapper.clearExpiredLock();
    }
}
